<template>
	<view v-if="!loading">
		<view class="fixed">
			<cu-custom bgColor="bg-shadeTop text-white" :isBack="true">
				<block slot="backText">返回</block>
			</cu-custom>
		</view>
		<swiper class="screen-swiper round-dot margin-top-xl" :indicator-dots="true" :circular="true" :autoplay="true"
			interval="5000" duration="500" style="height: 750rpx;">
			<swiper-item v-for="(item,index) in goodsInfo.spuUrls" :key="index" :data-url="item" @tap="viewImage">
				<image :src="item" mode="scaleToFill"></image>
			</swiper-item>
		</swiper>
		<view class="solid-top  bg-white  margin-tb-xs radius">
			<view class="flex justify-between align-center paddomgnew">
				<text class="text-price text-xl padding-right-xs"
					:class="'text-'+ theme.themeColor">{{goodsInfo.highPrice != goodsInfo.lowPrice ?  goodsInfo.lowPrice+' - '+goodsInfo.highPrice: goodsInfo.highPrice}}</text>
			</view>
			<view class="cu-bar margin-top-xs" style="min-height:0rpx;" v-if="couponList.length >0">
				<view class="action" style="margin-left: 0rpx;">
					<view v-for="(item,index) in  couponList" class="margin-right-xs">
						<view v-if="index<=2" class='coupons_css'>{{item.couponName}}
							<view class="leftdot"></view>
							<view class="rightdot"></view>
						</view>
					</view>
				</view>
				<view class="action" style="margin-right: 0rpx;">
					<button class="cu-btn round sm" :class="'bg-' + theme.themeColor" @tap="couponModal=true">领 券
					</button>
				</view>
			</view>
			
			<view class="pddlet">
				<view class="text-black marbootm">{{goodsInfo.name}}</view>
				<view class="text-grey text-sm" v-if="goodsInfo.subTitle">{{goodsInfo.subTitle}}</view>
			</view>

			<view class="margin-top-xs border-top">
				<view class="flex align-center justify-between">
					<!-- #ifdef MP-WEIXIN -->
					<button @tap="goodsShare" open-type="share" class="cu-btn bg-white text-xl padding-lr">
						<view class="flex align-center">
							<text class="cuIcon-forward"></text><text class="text-sm">分享</text>
						</view>
					</button>
					<!-- #endif -->
					
					<!-- #ifdef APP-PLUS -->
					<button @tap="goodsShareApp" open-type="share" class="cu-btn bg-white text-xl padding-lr">
						<view class="flex align-center">
							<text class="cuIcon-forward"></text><text class="text-sm">分享啊</text>
						</view>
					</button>
					<!-- #endif -->
					
					<!-- #ifdef H5 -->
					<button  @tap="clickShare" open-type="share" class="cu-btn bg-white text-xl padding-lr">
						<view class="flex align-center">
							<text class="cuIcon-forward"></text><text class="text-sm">分享</text>
						</view>
					</button>
					<u-toast ref="uToast" />
					<!-- #endif -->
					<view class="text-xl padding-lr flex align-center" @tap="onCollect">
						<view class="flex align-center" v-if="goodsInfo.collectId">
							<text class="cuIcon-favorfill" :class="'text-'+theme.themeColor"></text><text
								class="text-sm">取消收藏</text>
						</view>
						<view class="flex align-center" v-if="!goodsInfo.collectId">
							<text class="cuIcon-favor"></text><text class="text-sm">收藏</text>
						</view>

					</view>
					<!-- <view class="text-xl padding-lr flex align-center" @tap="onDownPriceNotify">
						<text class="cuIcon-recharge"></text><text class="text-sm">降价通知</text>
					</view> -->
				</view>
			</view>
		</view>

		<view class="cu-bar bg-white  margin-tb-xs radius" v-if="goodsInfo.enableSpecs == '1'">
			<view class="flex align-center" @tap="selectSku('1')" style="width: 100%;">
				<view class="flex-sub text-sm">
					<view class="text-gray margin-left-sm">选择</view>
				</view>
				<view class="flex-treble text-sm text-black padding-tb-xs"
					v-if="goodsSpuSpecsList && goodsSpuSpecsList.length >0">
					<text v-for="(item,index) in goodsSpuSpecsList" :key="index" v-if="!selectedName">
						{{item.specsName}}{{index == goodsSpuSpecsList.length-1 ?'' :' / '}}
					</text>
					<text v-if="selectedName" class="hx-overflow-1">
						已选：{{selectedName}}
					</text>
					<view>
						<view
							v-for="(v,i) in goodsSpuSpecsList[0].goodsSkuSpecsValues.length >=2 ? 2: goodsSpuSpecsList[0].goodsSkuSpecsValues.length"
							:key="i" class="cu-avatar radius  margin-right-sm" style="margin-left: 0rpx;"
							:style="'background-image:url(' + goodsSpuSpecsList[0].goodsSkuSpecsValues[i].picUrl + ')'">
						</view>
						<text class="padding-xs radius text-sm" v-if="goodsSpuSpecsList[0].goodsSkuSpecsValues"
							:class="'bg-'+ theme.themeColor">共{{goodsSpuSpecsList[0].goodsSkuSpecsValues.length}}种{{goodsSpuSpecsList[0].specsName}}可选</text>
					</view>
				</view>
				<view class="flex-sub text-sm text-gray text-right">
					<text class="cuIcon-right margin-right-sm"></text>
				</view>
			</view>
		</view>
		
		<!-- 发货 -->
		<!-- <view class="cu-bar bg-white  margin-tb-xs radius">
			<navigator class="flex align-center" style="width: 100%;" hover-class="none"
				url="/pages/user/user-address/index">
				<view class="flex-sub text-sm">
					<view class="text-gray margin-left-sm">发货</view>
				</view>
				<view class="flex-treble text-sm text-black padding-tb-xs" v-if="goodsInfo.freightTemplate">
					{{goodsInfo.freightTemplate.address}}
					<text class="text-gray padding-lr-xs">|</text>
					<text>{{'快递：'+getPostage}}</text>
					<view class="padding-tb-xs text-gray text-sm" v-if="addressInfo">
						配送至：{{addressInfo.provinceName}} {{addressInfo.cityName}} {{addressInfo.countyName}}
					</view>
				</view>
				<view class="flex-sub text-sm text-gray text-right">
					<text class="cuIcon-right margin-right-sm"></text>
				</view>
			</navigator>
		</view> -->
		
		
		<!-- 商品评价 -->
		<!-- <view class="cu-card bg-white  margin-tb-xs radius">
			<view class="flex solid-bottom justify-between">
				<text class="margin-left-sm margin-tb-sm">商品评价</text>
				<text class="margin-right-sm margin-tb-sm" v-if="goodsAppraiseList && goodsAppraiseList.length >0"
					@tap="tapGoodsAppraise">查看更多 <text class="cuIcon-right"></text></text>
			</view>
			<view v-if="goodsAppraiseList && goodsAppraiseList.length >0" v-for="(item,index) in goodsAppraiseList"
				:key="index">
				<view class="cu-item">
					<view class="cu-list menu-avatar">
						<view class="cu-item">
							<view class="cu-avatar round lg" :style="'background-image:url(' + item.avatarUrl + ')'">
							</view>
							<view class="content flex-sub">
								<view>{{item.nickName}}</view>
								<view class="flex justify-between">
									<uni-rate :value="item.goodsScore" :readonly="true" :size="20" color="#bbb"
										active-color="red" />
								</view>
							</view>
						</view>
					</view>
					<view class="text-content padding-lr margin-tb-sm">
						{{item.content || '该用户没有填写文本。'}}
					</view>
					<view class="grid flex-sub padding-lr col-3 grid-square solid-bottom">
						<view class="bg-img" :style="'background-image:url(' + itemPic + ')'"
							v-for="(itemPic,index) in item.picUrls " v-if="index<3" :key="index">
						</view>
					</view>
				</view>
			</view>
		</view> -->
		
		
		<view class="bg-white  margin-tb-xs radius">
			<!-- <view class="flex justify-center padding-tb-lg spxq-con">
				<text>商品详情</text>
			</view> -->
			<!-- #ifdef H5 || APP-PLUS -->
				<u-parse :html="goodsInfo.description"></u-parse>
			<!-- #endif -->
		
			<!-- #ifdef MP-WEIXIN -->
			  <u-parse :content="goodsInfo.description" />
			<!-- #endif -->
			
		</view>
		<view class="cu-tabbar-height"></view>
		<!-- 底部操作栏 -->
		<view class="cu-bar bg-white tabbar border shop foot">
			<view class="action" @tap="toHome">
				<view class="cuIcon-home"></view>
				<text>首页</text>
			</view>
			<!-- <button class="action" open-type="contact">
				<view class="cuIcon-service text-green"></view>
				客服
			</button> -->
			<view class="action" @tap="toCart">
				<view class="cuIcon-cart">
					<view class="cu-tag badge" v-if="shoppingCartCount>0">{{shoppingCartCount}}</view>
				</view>
				<text>购物车</text>
			</view>
			<view class="btn-group">
				<button class="cu-btn round shadow-blur" :class="'bg-'+ theme.matchColor"
					@tap="selectSku('2')">加入购物车</button>
				<button class="cu-btn round shadow-blur" :class="'bg-'+ theme.themeColor"
					@tap="selectSku('3')">立即购买</button>
			</view>

		</view>
		<vk-data-goods-sku-popup ref="skuPopup" v-model="skuModal" :localdata="goodsInfo"
			skuArrName="goodsSkuSpecsValues" skuListName="goodsSkus" specListName="goodsSpuSpecs"
			:relationId="relationId" :mode="modelTpye" @close="skuClose" @shoppingCartEvent="shoppingCartEvent">
		</vk-data-goods-sku-popup>
		<coupon-model :spuId="goodsInfo.id" :couponModal="couponModal" @changeCouponModal="couponModal=$event">
		</coupon-model>
	</view>
</template>

<script>
	import UParse from '@/components/gaoyia-parse/parse.vue';
	import Skeleton from '@/components/skeleton/index.vue';
	import CouponModel from '@/components/coupon-model/index.vue';
	import {
		getCount as getShoppingCartCount
	} from '@/api/shoppingcart.js';
	import {
		getPage as getCouponPage
	} from '@/api/couponinfo.js';
	import {
		save as saveCollect
	} from '@/api/usercollect.js';
	import {
		getById as goodsSpuById
	} from '@/api/goodsspu.js';
	import {
		getPage as goodsAppraisePage
	} from '@/api/goodsappraise.js';
	import {
		defaultAddress
	} from '@/api/useraddress.js';
	export default {
		components: {
			UParse,
			Skeleton,
			CouponModel
		},
		data() {
			return {
				loading: true,
				shoppingCartCount:'',
				theme: getApp().globalData.theme,
				goodsInfo: {}, // 商品详情
				freightTemplate: {}, //运费模版
				goodsAppraiseList: [], // 商品评论
				addressInfo: null,
				goodsSpuSpecsList: [],
				skuModal: false,
				selectedSku: {},
				selectedName: '',
				modelTpye: '', //1:都显示  2:只显示购物车 3:只显示立即购买 4:显示缺货按钮 默认 1
				relationId: '', // 关联id
				couponList: [],
				couponModal: false
			};
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}
			const userInfo = this.$store.state.user.userInfo
			let userNumber = userInfo ? '&share_user_number=' + userInfo.userNumber : ''
			return {
				title: this.goodsInfo.name,
				imageUrl: this.goodsInfo.spuUrls[0],
				path: "subpkg/goods/goods-detail/index?id=" + this.goodsInfo.id + userNumber
			}
		},
		onShow() {
			this.shoppingCartEvent()
			// console.log(this.shoppingCartCount + '---------')
		},
		onLoad(props) {
			getApp().initPage(props).then(res => {
				if (props.id) {
					this.getDetail(props.id);
					this.getDefaultAddress();
				}
			})
		},
		computed: {
			getPostage() {
				if (this.goodsInfo.freightTemplate) {
					if (this.goodsInfo.freightTemplate.isInclPostage == '1') {
						return '包邮';
					}
					if (this.goodsInfo.freightTemplate.isInclPostageByIf == '1') {
						return '满' + this.goodsInfo.freightTemplate.fullAmount + '元包邮';
					}
					return this.goodsInfo.freightTemplate.firstFreight + "元起";
				} else {
					return null;
				}

			}
		},
		methods: {
			shoppingCartEvent() {
				getShoppingCartCount().then(res => {
					this.shoppingCartCount = res.data;
					// getApp().globalData.shoppingCartCount = res.data;
				})
			},
			skuClose(data) {
				this.selectedName = data.join(' ').trim()
			},
			/**
			 * 查询商品详情
			 */
			getDetail(id) {
				this.loading = true;
				goodsSpuById(id).then(res => {
					this.goodsInfo = res.data
					this.goodsSpuSpecsList = res.data.goodsSpuSpecs;
					this.getGoodsAppraise();
					this.getCouponPage();
					this.loading = false;
				}).catch(() => {
					this.loading = false;
				});
			},
			/**
			 * 查询最近两条商品评论
			 */
			getGoodsAppraise() {
				let page = {
					current: 1,
					size: 2,
					spuId: this.goodsInfo.id,
					descs: 'create_time'
				}
				goodsAppraisePage(page).then(res => {
					this.goodsAppraiseList = res.data.records
				})
			},
			/**
			 * 获取已登录用户默认收货地址
			 */
			getDefaultAddress() {
				let userInfo = uni.getStorageSync('user_info');
				if (userInfo && userInfo.id) {
					defaultAddress().then(res => {
						this.addressInfo = res.data
					})
				}

			},

			/**
			 * 跳转商品评论列表
			 */
			tapGoodsAppraise() {
				uni.navigateTo({
					url: "/subpkg/goods/goods-appraise/index?spuId=" + this.goodsInfo.id
				})
			},
			/**
			 * 跳转首页
			 */
			toHome() {
				uni.reLaunch({
					url: '/pages/home/index'
				})
			},
			/**
			 * 跳转购物车
			 */
			toCart() {
				uni.switchTab({
					url: '/pages/shopping-cart/index'
				});
			},
			/**
			 * sku选择
			 */
			selectSku(type) {
				this.modelTpye = type;
				if (this.goodsInfo.enableSpecs == '0') {
					this.selectedSku = this.goodsInfo.goodsSkus[0]
				}
				this.skuModal = true
			},
			getCouponPage() {
				getCouponPage({
					spuId: this.goodsInfo.id,
					current: 1,
					size: 3,
					descs: "create_time",
				}).then(response => {
					this.couponList = response.data.records
				})
			},
			//收藏
			onCollect() {
				saveCollect({
					spuId: this.goodsInfo.id,
					salesPrice: this.goodsInfo.lowPrice
				}).then(response => {
					this.goodsInfo.collectId = response.data.id;
					this.$emit("changeGoodsInfo", this.goodsInfo)
					uni.showToast({
						title: '收藏成功',
						icon: 'success',
						duration: 2000
					});
				})
			},
			//降价通知
			onDownPriceNotify() {
				uni.navigateTo({
					url: '/subpkg/goods/down-price-notify/index?spuId=' + this.goodsInfo.id + "&salesPrice=" + this
						.goodsInfo.lowPrice
				})
			},
			viewImage(e) {
				uni.previewImage({
					urls: this.goodsInfo.spuUrls,
					current: e.currentTarget.dataset.url
				});
			},
			
		
			goodsShare() {
				const userInfo = uni.getStorageSync('user_info')
				let userNumber = '&share_user_number=' + userInfo ? userInfo.userNumber : ''
				uni.share({
					provider: "weixin",
					// scene: "WXSceneSession",
					scene: 'WXSceneTimeline', // 分享到朋友圈
					type: 0,
					href: "subpkg/goods/goods-detail/index?id=" + this.goodsInfo.id + userNumber,
					title: this.goodsInfo.name,
					summary: this.goodsInfo.name,
					imageUrl: this.goodsInfo.spuUrls[0],
					success: function(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					}
				});
			},
			goodsShareApp() {
			  const userInfo = uni.getStorageSync('user_info');
			  let userNumber = userInfo ? '&share_user_number=' + userInfo.userNumber : '';
			
			 
			  // APP原生分享
			  uni.share({
			    provider: 'weixin',
			    type: 0,
			    href: 'subpkg/goods/goods-detail/index?id=' + this.goodsInfo.id + userNumber,
			    title: this.goodsInfo.name,
			    summary: this.goodsInfo.name,
			    imageUrl: this.goodsInfo.spuUrls[0],
			    success: function(res) {
			      console.log("分享成功");
			    },
			    fail: function(err) {
			      console.log("分享失败：" + JSON.stringify(err));
			    }
			  });
			 
			},
			clickShare(){
				// 获取当前页面的域名
				  let domain = window.location.origin;
				  // 复制链接
				  let link = domain + '/subpkg/goods/goods-detail/index?id=' + this.goodsInfo.id;
				  this.copyToClipboard(link)
				  // 显示提示消息
				  this.showToast()
				  // console.log(link)
			},
			// 复制文本到剪贴板
			copyToClipboard(text) {
			  let input = document.createElement('input');
			  input.setAttribute('readonly', 'readonly');
			  input.setAttribute('value', text);
			  document.body.appendChild(input);
			  input.setSelectionRange(0, text.length);
			  input.select();
			  document.execCommand('copy');
			  document.body.removeChild(input);
			},
            showToast() {
				this.$refs.uToast.show({
					title: '已复制，快去粘贴吧',
					type: 'success',
					icon: 'checkmark'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.cu-btn{
		padding: 0 30px;
	}
	.cu-tag.badge{
		top: -5px !important;
		right: 6px !important;
	}
	.marbootm{
		margin-bottom: 5px;
	}
	.pddlet{
		padding: 0 10px 10px;
	}
	.paddomgnew{
		padding: 5px 10px;
	}
	.border-top{
		border-top: 5px solid #ededed;
	}
	.share-button {
		width: 90rpx;
		position: relative;
		right: -20rpx;
		height: 60rpx;
		border-radius: 50px 0px 0px 50px;
	}

	.foot {
		.action {
			width: 110rpx !important;
		}
	}

	.coupons_css {
		height: 36upx;
		position: relative;
		margin-right: 20upx;
		text-align: center;
		line-height: 36upx;
		padding: 0 14upx;
		border: 1upx solid #ff3d36;
		border-radius: 10upx;
		font-size: 22upx;
		color: #ff3d36;
	}

	.leftdot {
		position: absolute;
		top: 13upx;
		left: -3upx;
		width: 6upx;
		height: 10upx;
		border-top-right-radius: 20upx;
		border-bottom-right-radius: 20upx;
		border: 1upx solid #ff3d36;
		background-color: #fff;
		border-left: 0;
	}

	.rightdot {
		position: absolute;
		top: 13upx;
		right: -3upx;
		width: 6upx;
		height: 10upx;
		border-top-left-radius: 20upx;
		border-bottom-left-radius: 20upx;
		border: 1upx solid #ff3d36;
		background-color: #fff;
		border-right: 0;
	}
</style>
